import { assetManager, AssetManager, Prefab, SpriteFrame ,Node } from "cc";

export enum Bundle_Name_E {
    Ass_Bundle = "frameBundle",
    Game_Bundle = "gameBundle",
    Main_Bundle = "mainBundle",
}

export interface bundleMap {
    [id: string]: AssetManager.Bundle;
}

export default class AssetMgr{

    private static inst:AssetMgr = null;

    public static get Inst():AssetMgr{
        if(!this.inst)this.inst = new AssetMgr();
        return this.inst;
    }

    protected mName: string = "资源管理";

    bundleMap: bundleMap = {};

    async startLoadBundle(): Promise<void> {
        //super.startLoadBase();

        console.log("bundle load ...");
    }

    async loadBaseComplete(){
        //super.loadBaseComplete();
    }

    /**
     * 获得一个bundle
     * @param bundleName bundle包名
     * @returns 获得的bundle包
     */
    async getOneBundle(bundleName: string) {
        return new Promise<AssetManager.Bundle>(resolve => {
            let bundle = this.bundleMap[bundleName];
            if (!bundle) {
                assetManager.loadBundle(bundleName, AssetManager.Bundle, (err, bun: AssetManager.Bundle) => {
                    if (err) {
                        resolve(null);
                        return;
                    }
                    this.addOneBundle(bundleName, bun);
                    resolve(bun);
                });
            } else {
                resolve(bundle);
            }
        });
    }


    getBundleByInstance(bundleName: string) {
        return this.bundleMap[bundleName];
    }

    async getOnePrefab(path: string, bundleName: string) {
        let bundle = await this.getOneBundle(bundleName);
        return new Promise<Prefab>(resolve => {
            bundle.load(path, Prefab, (err, prefab: Prefab) => {
                if (err) {
                    resolve(null);
                    return;
                }
                // console.log("加载分包_预制体：",prefab.name);
                resolve(prefab);
            });
        });
    }

    async getOneSpriteFrame(path: string, bundleName: string) {
        let bundle = await this.getOneBundle(bundleName);
        return new Promise<SpriteFrame>(resolve => {
            bundle.load(path, SpriteFrame, (err, prefab: SpriteFrame) => {
                if (err) {
                    console.log(err);
                    resolve(null);
                    return;
                }
                resolve(prefab);
            });
        });
    }

    /**
     * 往map中添加一个bundle
     * @param bundleName bundle名字
     * @param bundle bundle包
     */
    addOneBundle(bundleName: string, bundle: AssetManager.Bundle) {
        this.bundleMap[bundleName] = bundle;
    }

}
